package com.example.huadu_server.oss.service.impl;

import com.example.huadu_server.oss.config.OssConfig;
import com.example.huadu_server.oss.service.OssService;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OssConfig ossConfig;

    @Override
    public String uploadFile(MultipartFile file, String folderName) {
        // 构建文件路径
        String fileName = folderName + "/" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

        try {
            // 获取上传管理器和凭证
            UploadManager uploadManager = ossConfig.getUploadManager();
            String uploadToken = ossConfig.getUploadToken();

            // 上传文件到七牛云
            Response response = uploadManager.put(file.getBytes(), fileName, uploadToken);
            if (response.isOK()) {
                // 强制返回 HTTP 链接
                return "http://" + ossConfig.getDomain() + "/" + fileName;
            } else {
                throw new RuntimeException("文件上传失败: " + response.error);
            }
        } catch (Exception e) {
            throw new RuntimeException("文件上传异常: " + e.getMessage(), e);
        }
    }
}
